package com.kakarote.admin.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import com.kakarote.admin.controller.AdminUserController;
import com.kakarote.admin.entity.PO.AdminCompanySecuritySetting;
import com.kakarote.admin.entity.PO.AdminUser;
import com.kakarote.admin.mapper.AdminCompanySecuritySettingMapper;
import com.kakarote.admin.service.IAdminCompanySecuritySettingService;
import com.kakarote.admin.service.IAdminMessageService;
import com.kakarote.core.common.Const;
import com.kakarote.core.common.enums.SystemCodeEnum;
import com.kakarote.core.entity.AdminCompanySecuritySettingVO;
import com.kakarote.core.entity.BasePage;
import com.kakarote.core.entity.PageEntity;
import com.kakarote.core.entity.UserInfo;
import com.kakarote.core.exception.CrmException;
import com.kakarote.core.feign.admin.entity.AdminMessageBO;
import com.kakarote.core.feign.admin.entity.AdminMessageEnum;
import com.kakarote.core.redis.Redis;
import com.kakarote.core.servlet.ApplicationContextHolder;
import com.kakarote.core.servlet.BaseServiceImpl;
import com.kakarote.core.utils.UserUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.Serializable;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 企业安全设置表 服务实现类
 * </p>
 *
 * @author yangzenghui
 * @since 2023-08-28
 */
@Service
public class AdminCompanySecuritySettingServiceImpl extends BaseServiceImpl<AdminCompanySecuritySettingMapper,
        AdminCompanySecuritySetting> implements IAdminCompanySecuritySettingService {


    @Autowired
    private IAdminMessageService adminMessageService;

    @Autowired
    private Redis redis;

    /**
     * 查询字段配置
     *
     * @param id 主键ID
     * @return data
     * @author yangzenghui
     * @since 2023-08-28
     */
    @Override
    public AdminCompanySecuritySetting queryById(Serializable id) {
        return getById(id);
    }

    /**
     * Get the security setting*
     *
     * @param configType 配置类型 1.密码规则设置 2.登出规则设置
     * @return
     */
    @Override
    public AdminCompanySecuritySettingVO queryByConfigType(Integer configType) {

        //查询缓存
        String redisKey = Const.COMPANY_SECURITY_CONFIG_KEY + ":" + configType;
        Object redisResult = redis.get(redisKey);
        if (ObjectUtil.isNull(redisResult)) {
            //入参校验，只支持1，2类型
            if (configType > 2 || configType < 1) {
                throw new CrmException(SystemCodeEnum.SYSTEM_NO_VALID);
            }
            AdminCompanySecuritySetting securitySetting = lambdaQuery().eq(AdminCompanySecuritySetting::getConfigType,
                    configType).one();
            if (ObjectUtil.isNull(securitySetting)) {
                securitySetting = new AdminCompanySecuritySetting();
                securitySetting.setConfigType(configType);
                if (ObjectUtil.equal(configType, 1)) {
                    // 密码规则设置
                    securitySetting.setPwdValidPeriod(Integer.MAX_VALUE);
                    securitySetting.setEnforcePwdHistory(0);
                    securitySetting.setMinimumPwdLen(6);
                    securitySetting.setPwdCharRequire(1);
                    securitySetting.setPwdErrorNum(Integer.MAX_VALUE);
                    securitySetting.setChangePwdRule(1);
                } else {
                    securitySetting.setMaximumIdleTime(30);
                    securitySetting.setMaximumIdleTimeUnit(1);
                    securitySetting.setMaximumLoginFreeTime(30);
                    securitySetting.setMaximumLoginFreeTimeUnit(1);
                    securitySetting.setMultDeviceLogin(1);
                }
                save(securitySetting);
            }
            AdminCompanySecuritySettingVO vo = BeanUtil.copyProperties(securitySetting,
                    AdminCompanySecuritySettingVO.class);
            //存缓存
            redis.setex(redisKey, 3600 * 24 * 30, vo);
            return vo;
        } else {
            redis.expire(redisKey, 3600 * 24 * 30);
            return (AdminCompanySecuritySettingVO) redisResult;
        }
    }

    /**
     * *
     *
     * @param configType 配置类型 1.密码规则设置 2.登出规则设置
     * @param companyId  企业id
     * @return
     */
    @Override
    public AdminCompanySecuritySettingVO queryByConfigTypeAndCompanyId(Integer configType) {
        //查询缓存
        String redisKey = Const.COMPANY_SECURITY_CONFIG_KEY  + ":" + configType;
        Object redisResult = redis.get(redisKey);
        if (ObjectUtil.isNull(redisResult)) {
            //入参校验，只支持1，2类型
            if (configType > 2 || configType < 1) {
                throw new CrmException(SystemCodeEnum.SYSTEM_NO_VALID);
            }
            AdminCompanySecuritySetting securitySetting = lambdaQuery().eq(AdminCompanySecuritySetting::getConfigType,
                    configType)
                    .one();
            if (ObjectUtil.isNull(securitySetting)) {
                securitySetting = new AdminCompanySecuritySetting();
                securitySetting.setConfigType(configType);
                if (ObjectUtil.equal(configType, 1)) {
                    // 密码规则设置
                    securitySetting.setPwdValidPeriod(Integer.MAX_VALUE);
                    securitySetting.setEnforcePwdHistory(0);
                    securitySetting.setMinimumPwdLen(6);
                    securitySetting.setPwdCharRequire(1);
                    securitySetting.setPwdErrorNum(Integer.MAX_VALUE);
                    securitySetting.setChangePwdRule(1);
                } else {
                    securitySetting.setMaximumIdleTime(30);
                    securitySetting.setMaximumIdleTimeUnit(1);
                    securitySetting.setMaximumLoginFreeTime(30);
                    securitySetting.setMaximumLoginFreeTimeUnit(1);
                    securitySetting.setMultDeviceLogin(1);
                }
                save(securitySetting);


            }
            AdminCompanySecuritySettingVO vo = BeanUtil.copyProperties(securitySetting,
                    AdminCompanySecuritySettingVO.class);
            //存缓存
            redis.setex(redisKey, 3600 * 24 * 30, vo);
            return vo;

        } else {
            redis.expire(redisKey, 3600 * 24 * 30);
            return (AdminCompanySecuritySettingVO) redisResult;
        }

    }

    /**
     * 用户未登录时
     *
     * @param configType 配置类型 1.密码规则设置 2.登出规则设置
     * @param companyId  企业id
     * @return
     */
    @Override
    public AdminCompanySecuritySettingVO querySecuritySetting(Integer configType, Long companyId) {
        //查询缓存
        String redisKey = Const.COMPANY_SECURITY_CONFIG_KEY + companyId + ":" + configType;
        Object redisResult = redis.get(redisKey);
        if (ObjectUtil.isNull(redisResult)) {
            //入参校验，只支持1，2类型
            if (configType > 2 || configType < 1) {
                throw new CrmException(SystemCodeEnum.SYSTEM_NO_VALID);
            }
            AdminCompanySecuritySetting securitySetting = lambdaQuery().eq(AdminCompanySecuritySetting::getConfigType,
                    configType).one();
            if (ObjectUtil.isNull(securitySetting)) {
                throw new CrmException(SystemCodeEnum.SYSTEM_NO_VALID);
            }
            AdminCompanySecuritySettingVO vo = BeanUtil.copyProperties(securitySetting,
                    AdminCompanySecuritySettingVO.class);
            return vo;
        } else {
            return (AdminCompanySecuritySettingVO) redisResult;
        }

    }

    /**
     * 修改
     *
     * @param vo vo
     * @author yangzenghui
     * @since 2023-08-28
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(AdminCompanySecuritySettingVO vo) {

        AdminCompanySecuritySetting oldRecord = queryById(vo.getConfigId());
        saveOrUpdate(BeanUtil.copyProperties(vo, AdminCompanySecuritySetting.class));
        String redisKey = Const.COMPANY_SECURITY_CONFIG_KEY + ":" + vo.getConfigType();
        //更新缓存
        redis.setex(redisKey, 3600 * 24 * 30, vo);
        //update  compare old and new
        if (oldRecord.getConfigType().equals(1) && ObjectUtil.isNotNull(vo.getMinimumPwdLen()) && ObjectUtil.isNotNull(vo.getPwdCharRequire())) {
            if (!oldRecord.getMinimumPwdLen().equals(vo.getMinimumPwdLen()) || !oldRecord.getPwdCharRequire().equals(vo.getPwdCharRequire())) {
                //给所有员工发送密码规则变更提醒
                UserInfo userInfo = UserUtil.getUser();
                try {
                    List<Long> ids =
                            ApplicationContextHolder.getBean(AdminUserController.class).queryAllUserList(1).getData();
                    if (CollUtil.isNotEmpty(ids)) {
                        //设置企业所有员工密码为待更新状态
                        AdminUserServiceImpl adminUserService =
                                ApplicationContextHolder.getBean(AdminUserServiceImpl.class);
                        UserUtil.setUser(userInfo);
                        List<AdminUser> users = ids.stream().map(id -> {
                            AdminUser adminUser = new AdminUser();
                            adminUser.setUserId(id);
                            adminUser.setPwdUpdStatus(2);
                            return adminUser;
                        }).collect(Collectors.toList());
                        adminUserService.batchUpdPasswordUpdStatus(users);
                        //给企业所有员工发送密码规则变更提醒
                        AdminMessageBO adminMessageBO = new AdminMessageBO();
                        adminMessageBO.setMessageType(AdminMessageEnum.ADMIN_PWD_CHANGE_SYSTEM_NOTICE_MESSAGE.getType());
                        adminMessageBO.setTitle(AdminMessageEnum.ADMIN_PWD_CHANGE_SYSTEM_NOTICE_MESSAGE.getRemarks());
                        adminMessageBO.setUserId(userInfo.getUserId());
                        adminMessageBO.setIds(ids);
                        adminMessageService.addMessage(adminMessageBO);
                    }
                } finally {
                    UserUtil.removeUser();
                }


            }

        }


    }

    /**
     * 新增信息
     *
     * @param vo vo
     * @author yangzenghui
     * @since 2023-08-28
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void add(AdminCompanySecuritySettingVO vo) {
        saveOrUpdate(BeanUtil.copyProperties(vo, AdminCompanySecuritySetting.class));
        //存缓存
        String redisKey = Const.COMPANY_SECURITY_CONFIG_KEY +":" + vo.getConfigType();
        redis.setex(redisKey, 3600 * 24 * 30, vo);
    }


    /**
     * 查询所有数据
     *
     * @param search 搜索条件
     * @return list
     * @author yangzenghui
     * @since 2023-08-28
     */
    @Override
    public BasePage<AdminCompanySecuritySetting> queryPageList(PageEntity search) {
        return lambdaQuery().page(search.parse());
    }

    /**
     * 根据ID列表删除数据
     *
     * @param ids ids
     * @author yangzenghui
     * @since 2023-08-28
     */
    @Override
    public void deleteByIds(List<Serializable> ids) {
        if (ids == null || ids.isEmpty()) {
            return;
        }
        removeByIds(ids);
    }

}
